import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_mode/zyj/db/db.dart';
import 'package:flutter_mode/zyj/model/base_data.dart';
import 'package:flutter_mode/zyj/model/user.dart';
import 'package:flutter_mode/zyj/net/dio_manager.dart';
import 'package:flutter_mode/zyj/redux/main_redux.dart';
import 'package:flutter_mode/zyj/redux/user_reducer.dart';
import 'dart:convert';

import 'package:flutter_mode/zyj/utils/sp.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:redux/redux.dart';
import 'package:rxdart/rxdart.dart';

//共享元素动画
class HeroPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HeroPage();
  }
}

class _HeroPage extends State<HeroPage> with TickerProviderStateMixin {
  bool isLogin = false;

  var _userController = TextEditingController();
  var _pwdController = TextEditingController();

  @override
  void initState() {
    super.initState();
    SpManager.singleton.getString("userAccount").then((account) {
      _userController.text = account;
    });
    SpManager.singleton.getString("pwd").then((pwd) {
      _pwdController.text = pwd;
    });
  }

  onLoginClick() async {
    if (_userController.text.toString().isEmpty) {
      Fluttertoast.showToast(msg: "用户名不能为空",toastLength: Toast.LENGTH_SHORT,backgroundColor: Color(0xff0000));
//      Fluttertoast.showToast(
//          msg: "用户名不能为空", toastLength: Toast.LENGTH_SHORT, bgcolor: "#ff0000");
      return;
    }
    if (_pwdController.text.toString().isEmpty) {
      Fluttertoast.showToast(msg: "密码不能为空",toastLength: Toast.LENGTH_SHORT,backgroundColor: Color(0x00ff00));
//      Fluttertoast.showToast(
//          msg: "密码不能为空", toastLength: Toast.LENGTH_SHORT, bgcolor: "#00ff00");
      return;
    }
    login();
  }

  loading(bool isLoading) {
    setState(() {
      isLogin = isLoading;
    });
  }

  login() async {
    loading(true);
    var param = json.encode({
      "username": _userController.text.toString(),
      "password": _pwdController.text.toString()
    });
    /*Response response = await DioManager.singleton.dio
        .post("app/main/login.json",
            data: FormData.from({
              "param": param,
            }))
        .whenComplete(() {
      loading(false);
    });
    ResultData result = ResultData.fromJson(response.data);
    print(response.data);
    if (result.success) {
      var user = User.fromJson(result.data);
      SpManager.singleton.save("userAccount", _userController.text.toString());
      SpManager.singleton.save("pwd", _pwdController.text.toString());
      DbManager.singleton.clear().then((_) {
        DbManager.singleton.save(user);
      }).then((_) {
        store.dispatch(UpdateUserAction(user));
        Navigator.of(context).pushReplacement(
            new MaterialPageRoute<Null>(builder: (BuildContext context) {
          return LoginSuccessPage();
        }));
      });
    } else {
      loading(false);
    }*/
    DioManager.singleton.post("app/main/login.json", data: FormData.fromMap({
      "param": param,
    })).whenComplete(() {
      loading(false);
    }).then((result){
      if (result.success) {
        var user = User.fromJson(result.data);
        SpManager.singleton.save("userAccount", _userController.text.toString());
        SpManager.singleton.save("pwd", _pwdController.text.toString());
        DbManager.singleton.clear().then((_) {
          DbManager.singleton.save(user);
        }).then((_) {
          store.dispatch(UpdateUserAction(user));
          Navigator.of(context).pushReplacement(
              new MaterialPageRoute<Null>(builder: (BuildContext context) {
                return LoginSuccessPage();
              }));
        });
      } else {
        loading(false);
      }
    });
  }

  late Store _store;

  Store get store => _store;

  @override
  Widget build(BuildContext context) {
    var loginButtonWidegt;
    if (isLogin) {
      AnimationController animationController = new AnimationController(
          vsync: this, duration: Duration(milliseconds: 2000));
      Animation<Color> animation =
          new Tween(begin: Colors.white, end: Colors.black)
              .animate(animationController);
      loginButtonWidegt = CircularProgressIndicator(
        backgroundColor: Colors.white,
        valueColor: animation,
      );
    } else {
      loginButtonWidegt = Text('登录', style: TextStyle(color: Colors.white));
    }
    final logo = Hero(
      tag: 'hero',
      child: CircleAvatar(
        backgroundColor: Colors.transparent,
        radius: 48.0,
        child: Image.asset('images/icon_header.jpg'),
      ),
    );

    final userName = Container(
      margin: EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.circular(50.0)),
      child: TextField(
          keyboardType: TextInputType.text,
          controller: _userController,
          autofocus: false,
          obscureText: false,
          decoration: InputDecoration(
              hintText: '请输入用户名',
              contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
              border: InputBorder.none)),
    );

    final password = Container(
      decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.circular(50.0)),
      child: TextField(
          controller: _pwdController,
          autofocus: false,
          obscureText: true,
          decoration: InputDecoration(
              hintText: '请输入密码',
              contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
              border: InputBorder.none)),
    );

    final loginButton = SizedBox(
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 16.0),
        child: ElevatedButton(
          // color: Colors.lightBlueAccent,
          onPressed: onLoginClick,
          child: loginButtonWidegt,
          // shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
        ),
      ),
      width: double.infinity,
      height: 80,
    );

    final forgotLabel = ElevatedButton(
      child: Text(
        '忘记密码?',
        style: TextStyle(color: Colors.black54),
      ),
      onPressed: () {},
    );

    var globalKey = GlobalKey();
    return StoreBuilder<MainRedux>(
      builder: (context, store) {
        _store = store;
        return Scaffold(
          key: globalKey,
          backgroundColor: Colors.white,
          body: SingleChildScrollView(
            child: Container(
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    logo,
                    SizedBox(height: 48.0),
                    userName,
                    SizedBox(height: 8.0),
                    password,
                    SizedBox(height: 24.0),
                    loginButton,
                    forgotLabel,
                  ],
                ),
              ),
              margin: EdgeInsets.fromLTRB(20, 100, 20, 0),
            ),
          ),
        );
      },
    );
  }
}

class LoginSuccessPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _LoginSuccessPage();
  }
}

class _LoginSuccessPage extends State<LoginSuccessPage> {
  var user;

  @override
  void initState() {
    super.initState();
    DbManager.singleton.get().then((datas) {
      user = datas[0];
      setState(() {});
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    final logo = Hero(
      tag: 'hero',
      child: Padding(
        padding: EdgeInsets.all(16.0),
        child: CircleAvatar(
          radius: 72.0,
          backgroundColor: Colors.transparent,
          backgroundImage: AssetImage('images/icon_header.jpg'),
        ),
      ),
    );

    final welcome = Padding(
      padding: EdgeInsets.all(8.0),
      child: Text(
        "${user == null ? "" : user["accountName"] ?? ""}",
        style: TextStyle(fontSize: 28.0, color: Colors.white),
      ),
    );

    final text = Padding(
      padding: EdgeInsets.all(8.0),
      child: Text(
        'Flutter is Google’s mobile app SDK for crafting high-quality native interfaces on iOS and Android in record time. Flutter works with existing code, is used by developers and organizations around the world, and is free and open source.',
        style: TextStyle(fontSize: 16.0, color: Colors.white),
      ),
    );

    final body = Container(
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.all(28.0),
      decoration: BoxDecoration(
        gradient: LinearGradient(colors: [
          Colors.blue,
          Colors.lightBlueAccent,
        ]),
      ),
      child: Column(
        children: <Widget>[logo, welcome, text],
      ),
    );
    return Scaffold(
      body: body,
    );
  }
}
